package net.lzzy.dao;

import net.lzzy.entity.Comment;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

public interface CommentRepository extends JpaRepository<Comment, Integer> {

    public List<Comment> findByAuthorAndArticleId(String author, Integer aId);

    public List<Comment> findByAuthorOrArticleId(String author, Integer aId);

    public List<Comment> findByArticleIdGreaterThanEqual(Integer num);

    public List<Comment> findByAuthorContains(String author);

    public List<Comment> findAllByOrderByArticleId();

    public void deleteById(Integer id);

    @Query("SELECT c from t_comment c WHERE c.articleId = ?1")
    public List<Comment> selectCommentByArticleId(Integer id);

    //nativeQuery为true，使用原生的SQL语句，否则使用JPQL
    @Query(value = "SELECT * from t_comment c WHERE a_id = ?1", nativeQuery = true)
    public List<Comment> selectCommentByArticleId2(Integer id);


    //更改数据库（增删改时）需要Modifying和Transactional注解
    @Transactional
    @Modifying
    @Query(value = "INSERT INTO t_comment(author, content, a_id) values(?1, ?2, ?3)", nativeQuery = true)
    public int addComment(String author, String content, Integer aId);

    @Transactional
    @Modifying
    @Query("UPDATE t_comment c SET c.content = ?1 WHERE c.id = ?2")
    public int updateCommentById(String content, Integer id);

    @Transactional
    @Modifying
    @Query("delete from t_comment c where c.id = ?1")
    public int delCommentById(Integer id);
}
